/**
 * 日期时间格式化
 * @param time 时间
 * @param pattern 格式化模式，默认为 {y}-{m}-{d} {h}:{i}:{s}
 * @returns 格式化后的时间字符串
 */
export function parseTime(
  time: string | number | Date,
  pattern?: string
): string {
  if (!time) {
    return "";
  }

  let date: Date;
  if (typeof time === "object") {
    date = time;
  } else {
    if (typeof time === "string" && /^[0-9]+$/.test(time)) {
      time = parseInt(time);
    } else if (typeof time === "string") {
      time = time.replace(/-/g, "/");
    }

    if (typeof time === "number" && time.toString().length === 10) {
      time = time * 1000;
    }

    date = new Date(time);
  }

  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  };

  const timeStr = pattern || "{y}-{m}-{d} {h}:{i}:{s}";

  return timeStr.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key];
    // 注意: getDay() 返回 0 是星期天
    if (key === "a") {
      return ["日", "一", "二", "三", "四", "五", "六"][value];
    }

    if (result.length > 0 && value < 10) {
      value = "0" + value;
    }

    return value.toString() || "0";
  });
}

/**
 * 下载文件
 * @param response Blob响应对象或其他数据
 * @param fileName 文件名称
 */
export function download(response: any, fileName?: string): void {
  if (!fileName) {
    fileName = "download_" + new Date().getTime() + ".xlsx";
  }

  if (response.type && response.type.includes("application/json")) {
    // 如果是json响应，说明接口出错
    const reader = new FileReader();
    reader.onload = function () {
      try {
        const result = JSON.parse(reader.result as string);
        const message = result.msg || "下载文件失败";
        console.error(message);
      } catch (error) {
        console.error("下载文件失败");
      }
    };
    reader.readAsText(response);
    return;
  }

  // 创建blob链接
  const blob = new Blob([response], { type: "application/octet-stream" });
  const blobURL = window.URL.createObjectURL(blob);

  // 创建a标签并触发下载
  const downloadElement = document.createElement("a");
  downloadElement.style.display = "none";
  downloadElement.href = blobURL;
  downloadElement.download = fileName;
  document.body.appendChild(downloadElement);
  downloadElement.click();
  document.body.removeChild(downloadElement);

  // 释放blob链接
  window.URL.revokeObjectURL(blobURL);
}
